package com.kaifamiao.ajax.service.impl;

import com.kaifamiao.ajax.dao.StudentDao;
import com.kaifamiao.ajax.dao.impl.StudentDaoImpl;
import com.kaifamiao.ajax.entity.Student;
import com.kaifamiao.ajax.exception.DataAccessException;
import com.kaifamiao.ajax.exception.ServiceException;
import com.kaifamiao.ajax.service.StudentService;
import com.kaifamiao.ajax.utils.SnowflakeIdGenerator;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    private SnowflakeIdGenerator idGenerator = SnowflakeIdGenerator.getInstance();
    private StudentDao stuDao = new StudentDaoImpl();

    @Override
    public boolean save(Student s) throws ServiceException {
        try {
            // 为 Student实例 设置 对象标识符
            s.setId( idGenerator.generate() );
            return stuDao.save( s );
        } catch ( DataAccessException cause ) {
            throw new ServiceException( "保存学生信息时发生错误" , cause);
        }
    }

    @Override
    public boolean update(Student s) throws ServiceException {
        try {
            return stuDao.update( s );
        } catch ( DataAccessException cause ) {
            throw new ServiceException( "更新学生信息时发生错误" , cause);
        }
    }

    @Override
    public boolean remove(Long id) throws ServiceException {
        try {
            return stuDao.remove( id );
        } catch ( DataAccessException cause ) {
            throw new ServiceException( "删除学生信息时发生错误" , cause);
        }
    }

    @Override
    public List<Student> loadAll() throws ServiceException {
        try {
            return stuDao.findAll();
        } catch ( DataAccessException cause ) {
            throw new ServiceException( "查询学生信息时发生错误" , cause);
        }
    }

    @Override
    public Student load(Long id) throws ServiceException {
        try {
            return stuDao.find(id);
        } catch ( DataAccessException cause ) {
            throw new ServiceException( "查询学生信息时发生错误" , cause);
        }
    }
}
